/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Portions created by the Initial Developer are
 * Copyright (C) 2012 the Initial Developer.
 * All Rights Reserved.
 *
 * The Original Code is this.
 *
 * The Initial Developer of the Original Code is the author below.
 */
/**
 * @file SessionContext.cpp
 * @brief auto generated.
 * @author K.Ozaki
 * @date 2011/07/21
 */

#include "semi/SessionContext.h"

namespace semi {

SessionContext::SessionContext(std::string filename, int filesize, bool lk) :
    SharedContext::SharedContext(filename, filesize, lk, false) {
}

SessionContext::~SessionContext() {
    this->end();
}

void SessionContext::terminateAll() {

    semi::posix::SharedMemory
            mems(current_mem_names, sizeof(SharedMemoryNames));
    SharedMemoryNames* nms = (SharedMemoryNames*) mems.get();
    // for (semi::util::IndexMap::iterator iter = semi::posix::SharedContext::memkeys.begin(); iter
    //         != semi::posix::SharedContext::memkeys.end(); ++iter) {
    //     std::string key = util::StringUtil::trim((std::string) iter->first);
    // }

    std::cout << "  SessionContext::terminateAll " << std::endl;

    for (int i = 0; i < (sizeof(nms->names) / sizeof(nms->names[0])); i++) {
        std::string nm = (nms->names[i]);
        if (0 == nm.length() && 0 == nms->sizes[i])
            continue;
        if ('0' == nms->scope[i]) // stable
            continue;

        semi::posix::SharedMemory mem(nm, nms->sizes[i]);
        bool ret = mem.terminate();
        //        if (!ret)
        //            std::cout << "SharedContext::terminate file:" << nm << " scope:"
        //                    << nms->scope[i] << " fail!" << std::endl;
        memset(nms->names[i], 0, sizeof(nms->names[i]));
        nms->sizes[i] = 0;
        nms->scope[i] = '0';

        semi::posix::Semaphore sem(nm);
        sem.unlink();
        //        sem.terminate();
    }
    mems.end();
}

}
